<script setup lang="ts">
import { ref, onMounted, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import axios from "axios";

const SEARCH_HISTORY_KEY = 'video_search_history';
const router = useRouter();
const route = useRoute();
const searchHistory = ref<string[]>([]);
const searchKey = ref("");
const inputRef = ref();
const allVideoTitles = ref<string[]>([]);
const suggestList = ref<string[]>([]);

const loadSearchHistory = () => {
  const history = localStorage.getItem(SEARCH_HISTORY_KEY);
  searchHistory.value = history ? JSON.parse(history) : [];
};

const clearSearchHistory = () => {
  searchHistory.value = [];
  localStorage.removeItem(SEARCH_HISTORY_KEY);
};

const deleteHistoryItem = (item: string) => {
  searchHistory.value = searchHistory.value.filter(historyItem => historyItem !== item);
  localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(searchHistory.value));
};


const onSearch = () => {
  // 如果输入框为空，搜索全部（传递空字符串）
  const searchTerm = searchKey.value.trim() || "";
  
  // 只有当搜索关键词不为空时才保存到历史
  if (searchKey.value.trim()) {
    let history = [searchKey.value, ...searchHistory.value.filter(item => item !== searchKey.value)];
    if (history.length > 8) history.length = 8;
    localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(history));
  }
  
  // 跳转回 Video 页面并带上搜索关键字
  router.push({ name: "Video", query: { search: searchTerm } });
};

const filteredHistory = computed(() => {
  // 始终显示所有历史记录，不进行筛选
  return searchHistory.value;
});

const completeFromHistory = (item: string) => {
  searchKey.value = item;
  // 自动搜索并跳转
  onSearch();
};

const completeFromSuggest = (item: string) => {
  searchKey.value = item;
  onSearch();
};

const back = () => {
  // 返回时不带search参数
  router.push({ name: "Video" });
};

const fetchAllTitles = async () => {
  const res = await axios.get("http://localhost:3000/api/video-list");
  allVideoTitles.value = res.data.map((item: any) => item.name);
};

// 监听路由参数变化，处理从Video页面传来的搜索关键词
watch(() => route.query.search, (newSearch) => {
  if (newSearch && typeof newSearch === 'string') {
    searchKey.value = newSearch;
  }
}, { immediate: true });

watch(searchKey, (val) => {
  if (!val.trim()) {
    suggestList.value = [];
    return;
  }
  suggestList.value = allVideoTitles.value.filter(title =>
    title.toLowerCase().includes(val.trim().toLowerCase())
  ).slice(0, 8);
});

onMounted(() => {
  loadSearchHistory();
  fetchAllTitles();
  // 检查是否有搜索参数
  if (route.query.search && typeof route.query.search === 'string') {
    searchKey.value = route.query.search;
  }
  // 页面加载后自动聚焦输入框
  inputRef.value && inputRef.value.focus();
});
</script>

<template>
  <div class="search-history-page">
    <div class="sticky-header">
      <van-nav-bar
        left-text="返回"
        left-arrow
        @click-left="back"
        title="搜索"
        class="nav-bar"
      />
      <div class="search-bar">
        <el-input
          ref="inputRef"
          v-model="searchKey"
          @keyup.enter="onSearch"
          placeholder="搜索视频内容..."
          clearable
          class="search-input"
          :show-clear="true"
        />
      </div>
      <div v-if="suggestList.length" class="suggest-list">
        <div
          v-for="item in suggestList"
          :key="item"
          class="suggest-item"
          @click="completeFromSuggest(item)"
        >
          {{ item }}
        </div>
      </div>
    </div>
    
    <div class="content-area">
      <div class="content-section">
        <div class="section-header">
          <h3 class="section-title">
            <van-icon name="clock-o" class="title-icon" />
            历史搜索记录
          </h3>
          <span class="history-count">{{ filteredHistory.length }}条记录</span>
        </div>
        
        <div v-if="filteredHistory.length" class="history-list">
          <div
            v-for="item in filteredHistory"
            :key="item"
            class="history-item"
            @click="completeFromHistory(item)"
          >
            <div class="history-content">
              <van-icon name="search" class="history-icon" />
              <div class="history-text">
                {{ item }}
              </div>
            </div>
            <van-icon 
              name="cross" 
              class="delete-icon" 
              @click.stop="deleteHistoryItem(item)"
            />
          </div>
          
          <div class="clear-section">
            <el-button 
              type="text" 
              size="small" 
              @click="clearSearchHistory" 
              class="clear-btn"
            >
              <van-icon name="delete-o" class="clear-icon" />
              清空历史记录
            </el-button>
          </div>
        </div>
        
        <div v-else class="empty-state">
          <van-icon name="search" class="empty-icon" />
          <p class="empty-text">暂无历史记录</p>
          <p class="empty-subtext">开始搜索，记录会显示在这里</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.search-history-page {
  padding: 0;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  width: 100%;
  z-index: 1000;
  background: #dff3fa;
}

.sticky-header {
  position: sticky;
  top: 46px;
  z-index: 100;
  background: #dff3fa;
  padding: 24px 20px 20px 20px;
  box-shadow: 0 4px 20px rgba(223, 243, 250, 0.3);
  border-radius: 0 0 24px 24px;
}

.content-area {
  padding: 24px 20px;
  background: linear-gradient(180deg, #f8fafc 0%, #e2e8f0 100%);
  min-height: calc(100vh - 200px);
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  justify-content: center;
}

.search-input {
  width: 100%;
  max-width: 400px;
}

:deep(.el-input__inner) {
  height: 44px;
  font-size: 16px;
  border-radius: 22px;
  border: none;
  background: transparent;
  backdrop-filter: none;
  box-shadow: none;
  transition: all 0.3s ease;
}

:deep(.el-input__inner):focus {
  background: transparent;
  box-shadow: none;
  transform: none;
}

:deep(.el-input__clear) {
  opacity: 1 !important;
  visibility: visible !important;
}

:deep(.el-input:hover .el-input__clear) {
  opacity: 1 !important;
  visibility: visible !important;
}

.content-section {
  background: white;
  border-radius: 24px;
  padding: 32px 24px 28px 24px;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  max-width: 800px;
  margin: 0 auto;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 2px solid #dff3fa;
  position: relative;
}

.section-header::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 60px;
  height: 2px;
  background: linear-gradient(90deg, #dff3fa 0%, transparent 100%);
}

.section-title {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  color: #2c5282;
  display: flex;
  align-items: center;
  gap: 10px;
  letter-spacing: -0.025em;
}

.title-icon {
  color: #dff3fa;
  font-size: 22px;
  background: linear-gradient(135deg, #dff3fa 0%, #b8e6f3 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.history-count {
  font-size: 13px;
  color: #2c5282;
  background: linear-gradient(135deg, #dff3fa 0%, #b8e6f3 100%);
  padding: 6px 14px;
  border-radius: 16px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(223, 243, 250, 0.3);
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.history-item {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 16px;
  padding: 18px 20px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid rgba(223, 243, 250, 0.3);
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
  backdrop-filter: blur(10px);
}

.history-item:hover {
  background: linear-gradient(135deg, #dff3fa 0%, #b8e6f3 100%);
  color: #2c5282;
  transform: translateY(-2px) scale(1.02);
  box-shadow: 0 8px 24px rgba(223, 243, 250, 0.3);
  border-color: rgba(223, 243, 250, 0.6);
}

.history-content {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.history-icon {
  color: #999;
  font-size: 16px;
}

.history-item:hover .history-icon {
  color: rgba(255, 255, 255, 0.8);
}

.history-text {
  font-size: 15px;
  font-weight: 600;
  line-height: 1.4;
  color: #1a202c;
}

.delete-icon {
  color: #ccc;
  font-size: 16px;
  transition: all 0.3s ease;
  cursor: pointer;
  padding: 4px;
  border-radius: 50%;
}

.delete-icon:hover {
  color: #ff4757;
  background: rgba(255, 71, 87, 0.1);
  transform: scale(1.1);
}

.history-item:hover .delete-icon {
  color: rgba(255, 255, 255, 0.8);
}

.history-item:hover .delete-icon:hover {
  color: #ff4757;
  background: rgba(255, 71, 87, 0.2);
}

.clear-section {
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid rgba(223, 243, 250, 0.3);
  text-align: center;
}

.clear-btn {
  color: #2c5282;
  font-size: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 auto;
  padding: 12px 28px;
  border-radius: 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border: 1px solid rgba(223, 243, 250, 0.4);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 600;
}

.clear-btn:hover {
  color: #2c5282;
  background: linear-gradient(135deg, #dff3fa 0%, #b8e6f3 100%);
  border-color: rgba(223, 243, 250, 0.6);
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(223, 243, 250, 0.3);
}

.clear-icon {
  font-size: 16px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #94a3b8;
}

.empty-icon {
  font-size: 56px;
  color: #dff3fa;
  margin-bottom: 20px;
  opacity: 0.7;
}

.empty-text {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 12px 0;
  color: #64748b;
}

.empty-subtext {
  font-size: 15px;
  margin: 0;
  color: #94a3b8;
  line-height: 1.5;
}

.suggest-list {
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid rgba(102, 126, 234, 0.2);
  border-radius: 16px;
  margin-top: 8px;
  box-shadow: 0 8px 30px rgba(102, 126, 234, 0.15);
  max-height: 200px;
  overflow-y: auto;
  position: absolute;
  width: 100%;
  max-width: 400px;
  z-index: 10;
  backdrop-filter: blur(10px);
}
.suggest-item {
  padding: 12px 20px;
  cursor: pointer;
  font-size: 15px;
  color: #1a202c;
  border-bottom: 1px solid rgba(102, 126, 234, 0.1);
  transition: all 0.3s ease;
}
.suggest-item:last-child {
  border-bottom: none;
}
.suggest-item:hover {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
}

</style> 